<template>
	<el-dialog title="编辑 Model" :visible.sync="dialogData.showEditDialog" width="450px" @close="cancelForm">
		<el-form
			ref="model"
			:model="model"
			:rules="rules"
			:label-position="labelPosition"
			:label-width="formLabelWidth"
		>
			<el-form-item label="商品名">
				<el-input v-model="model.productName"></el-input>
			</el-form-item>
			<el-form-item label="单价">
				<el-input v-model="model.productPrice"></el-input>
			</el-form-item>
			<el-form-item label="描述">
				<el-input v-model="model.productDes"></el-input>
			</el-form-item>
			<el-form-item label="库存">
				<el-input v-model="model.number"></el-input>
			</el-form-item>
			<el-form-item label="图片">
				<el-upload
					:action="fileUploadInfo.action"
					:headers="fileUploadInfo.headers"
					list-type="picture-card"
					:on-preview="handlePictureCardPreview"
					:on-remove="handleRemove"
					:on-success="handleSuccess"
					:before-upload="beforeUpload"
				>
					<i class="el-icon-plus"></i>
				</el-upload>
				<el-dialog :visible.sync="isShow.dialogVisible">
					<img width="100%" :src="isShow.dialogImageUrl" alt="" />
				</el-dialog>
			</el-form-item>
			<el-form-item label="种类">
				<!-- <el-input v-model="model.category"></el-input> -->
				<!-- <el-checkbox-group v-model="model.category">
					<el-checkbox
						v-for="item in roles"
						:key="item.id"
						:label="item.roleName"
						:name="item.roleName"
					></el-checkbox>
				</el-checkbox-group> -->
				
				<el-select v-model="model.productFkCategory" clearable placeholder="请选择">
				    <el-option
				      v-for="item in options"
				      :key="item.categoryId"
				      :label="item.categoryName"
				      :value="item.categoryId">
				    </el-option>
				  </el-select>
			</el-form-item>
		</el-form>

		<div slot="footer" class="dialog-footer">
			<el-button @click="cancelForm()">取 消</el-button>
			<el-button type="primary" @click="submitForm()">确 定</el-button>
		</div>
	</el-dialog>
</template>
<script>
export default {
	name: "ProductEdit",
	props: {
		dialogData: {
			type: Object,
			default: {
				id: 0,
				showEditDialog: false,
				editData: {},
			},
		},
	},
	data: function () {
		return {
			// 弹出框设置项
			formLabelWidth: "80px",
			labelPosition: "right",
			// model
			model: {
				id: 0,
				productName: "",
				productPrice: "",
				number: 0,
				productImage: "",
				// 当前商品种类
				productFkCategory: "",
			},
			// el-select 选择器的数据
			options: [],
			rules: {
				productName: [
					{
						required: true,
						message: "商品名不能为空",
						trigger: ["blur", "change"],
					},
				],
			},
			// 上传图片设置
			isShow : {
				dialogImageUrl: "",
				dialogVisible: false,
			},
			// dialogImageUrl: "",
			// dialogVisible: false,
			fileUploadInfo: {
				// 上传图片后端接口地址
				action: this.$Request.domain + "/file/upload",
				// 请求头包装的信息，如果无需验证则无需设置
				// headers: {
				// 	Token: this.$Storage.getItemForLs(this.$TestData.TOKEN_KEY),
				// },
			},
		};
	},
	methods: {
		// 初始化 el-select 选择器数据
		initCategory: function () {
			var self = this;
			this.$Request
				.fetch("/api/category/selectCategoryAll")
				.then((result) => {
					console.log(result);
					self.options = result.data;
				})
				.catch((error) => {
					this.$message.error(error);
				});
		},
		// 取消按钮
		cancelForm: function () {
			this.dialogData.showEditDialog = false;
		},
		// 提交按钮
		submitForm: function () {
			// 对 form 表单进行验证
			this.$refs["model"].validate((isValid) => {
				if (!isValid) {
					return;
				}

				// 包装 roles ，提交到后端接口
				// this.model.roles = this.model.roles.map((item) => {
				// 	var role = {};
				// 	var temp = this.roles.filter((ite) => ite.roleName == item)[0];
				// 	console.log(temp);
				// 	role.id = temp.roleId;
				// 	return role;
				// });
				// console.log(this.model);

				// 新增或修改 model
				//console.log(JSON.stringify(this.model));
				//console.log(this.model);
				console.log(this.model);
				var type = this.model.id == 0 ? "post" : "put";
				this.$Request
					.fetch_("/api/product/productInfo", type, this.model)
					.then((result) => {
						if (result.status == this.$Request.OK_CODE) {
							this.$refs["model"].resetFields();
							// 关闭对话框，刷新表格数据
							// 将对话框状态 showEditDialog 发送给父组件，由父组件来完成
							this.$emit("emitDialogData", false);
						} else {
							this.$message.info(result.message);
						}
					})
					.catch((error) => {
						this.$message.error(error);
					});
			});
			
		},
		// 上传图片相关方法
		// 移除图片调用函数
		handleRemove(file, fileList) {
			this.$Request
				.fetch("/api/resource/image?imagePath=" + file.src)
				.then((result) => {
					this.$message.info(result.message);
					this.model.images = this.model.images.filter((item) => item.src != file.src);
				})
				.catch((error) => {
					this.$message.info("删除出错。");
				});
		},
		// 图片预览函数
		handlePictureCardPreview(file) {
			this.isShow.dialogImageUrl = file.url;
			this.isShow.dialogVisible = true;
		},
		// 上传前图片验证
		beforeUpload: function (file) {
			const isJPG = file.type === "image/jpeg";
			const isLt4M = file.size / 1024 / 1024 < 4;
			// if (!isJPG) {
			// 	this.$message.error("图片只能是 JPG 格式!");
			// }
			if (!isLt4M) {
				this.$message.error("图片大小不能超过 4 MB!");
			}
			return isLt4M;
		},
		// 上传成功后处理函数
		handleSuccess: function (response, file, fileList) {
			if (response.status == 200) {
				this.model.productImage = this.$Request.domain + "" + response.data;
				// this.dialogImageUrl = "";
				// this.dialogVisible = false;
				// var image = {};
				// image.userId = this.user.id;
				// image.url = response.data;
				// image.src = response.data;
				// this.model.images.push(image);
			} else {
				this.$message.error("上传图片失败");
			}
		},
	},
	watch: {
		// 监听 dialogData.id，初始化模型
		dialogData: function (newVal, oldVal) {
			if (newVal.id == 0) {
				if (typeof this.$refs["model"] != "undefined") {
					// 重置 model
					this.model = {
						id: 0,
						productName: "",
						productPrice: "",
						number: 0,
						productImage: "",
						// 当前商品种类
						productFkCategory: "",
					};
					this.$refs["model"].resetFields();
				};
			} else {
				this.model = newVal.editData;
				// var url = "/api/account/user/" + this.dialogData.id;
				// this.$Request
				// 	.fetch(url)
				// 	.then((result) => {
				// 		this.model = result;
				// 		// 包装 roleName list
				// 		this.model.roles = this.model.roles.map((item) => {
				// 			return item.roleName;
				// 		});
				// 	})
				// 	.catch((error) => {
				// 		this.$message.info("没有数据。");
				// 	});
			}
		},
	},
	mounted() {
		this.initCategory();
	},
};
</script>
<style>
</style>
